package com.yanfan.zutai.controller;

import com.alibaba.fastjson2.JSON;
import com.yanfan.common.annotation.Anonymous;
import com.yanfan.common.annotation.Log;
import com.yanfan.common.config.RuoYiConfig;
import com.yanfan.common.core.controller.BaseController;
import com.yanfan.common.core.domain.AjaxResult;
import com.yanfan.common.core.domain.entity.SysUser;
import com.yanfan.common.core.text.Convert;
import com.yanfan.common.enums.BusinessType;
import com.yanfan.common.utils.StringUtils;
import com.yanfan.common.utils.file.FileUploadUtils;
import com.yanfan.common.utils.poi.ExcelUtil;
import com.yanfan.system.service.ISysUserService;
import com.yanfan.zutai.aop.SysInitData;
import com.yanfan.zutai.aop.SysQueryData;
import com.yanfan.zutai.domain.BDeviceManager;
import com.yanfan.zutai.domain.BDeviceZt;
import com.yanfan.zutai.domain.BDeviceZtBind;
import com.yanfan.zutai.domain.vo.BDeviceEmpower;
import com.yanfan.zutai.service.IBDeviceManagerService;
import com.yanfan.zutai.service.IBDeviceRealDataService;
import com.yanfan.zutai.service.IBDeviceZtBindService;
import com.yanfan.zutai.service.IBDeviceZtService;
import com.yanfan.zutai.util.Detect;
import com.yanfan.zutai.util.ImageUtils;
import io.swagger.annotations.ApiOperation;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.jdbc.core.BeanPropertyRowMapper;
import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import java.io.File;
import java.io.InputStream;
import java.util.Date;
import java.util.List;
import java.util.UUID;

/**
 * 云组态Controller
 *
 * @author ruoyi
 * @date 2022-05-21
 */
@RestController
@RequestMapping("/zutai/bDeviceZt")
public class BDeviceZtController extends BaseController {
    @Autowired
    private IBDeviceZtService bDeviceZtService;
    @Autowired
    private IBDeviceZtBindService bDeviceZtBindService;
    @Autowired
    private IBDeviceManagerService bDeviceManagerService;
    @Autowired
    private IBDeviceRealDataService bDeviceRealDataService;
    @Autowired
    private JdbcTemplate jdbcTemplate;
    @Autowired
    private ISysUserService userService;
/**
 * 查询云组态列表
 */
//    @GetMapping("/list")
//    @SysQueryData
//    public TableDataInfo list(BDeviceZt bDeviceZt)
//    {
//        startPage();
//        if(Detect.notEmpty(bDeviceZt.getQueryDeptId())){
//            bDeviceZt.setDeptIdStrs(bDeviceZt.getQueryDeptId());
//        }
//        List<BDeviceZt> list =bDeviceZtService.selectBDeviceZtList(bDeviceZt);
//        return getDataTable(list);
//    }
//    @GetMapping("/getZtData")
//    @SysQueryData
//    public AjaxResult getZtData(BDeviceZt bDeviceZt)
//    {
//        if(Detect.notEmpty(bDeviceZt.getQueryDeptId())){
//            bDeviceZt.setDeptIdStrs(bDeviceZt.getQueryDeptId());
//        }
//        if(Detect.isEmpty(bDeviceZt.getGuid())||Detect.isEmpty(bDeviceZt.getDeviceMac())){
//            return AjaxResult.error("系统中无此组态界面！");
//        }
//        BeanPropertyRowMapper<BDeviceZt> bDeviceDetailMapper = new BeanPropertyRowMapper<>(BDeviceZt.class);
//        String sql="select device_mac, device_name, page_name,device_zt_data from b_device_zt where guid=? and device_mac=?";
//        try {
//            bDeviceZt = jdbcTemplate.queryForObject(sql, bDeviceDetailMapper,bDeviceZt.getGuid(),bDeviceZt.getDeviceMac());//处理结果集EmptyResultDataAccessException，不做任何操作
//        }catch (EmptyResultDataAccessException e){
//        }
//        return AjaxResult.success(bDeviceZt);
//    }

    /**
     * 导出云组态列表
     */
    @Log(title = "云组态", businessType = BusinessType.EXPORT)
    @GetMapping("/export")
    @SysQueryData
    public AjaxResult export(BDeviceZt bDeviceZt) {
        List<BDeviceZt> list = bDeviceZtService.selectBDeviceZtList(bDeviceZt);
        ExcelUtil<BDeviceZt> util = new ExcelUtil<BDeviceZt>(BDeviceZt.class);
        return util.exportExcel(list, "bDeviceZt");
    }

//    /**
//     * 获取云组态详细信息
//     */
//    @GetMapping(value = "/{id}")
//    public AjaxResult getInfo(@PathVariable("id") Long id)
//    {
//        return AjaxResult.success(bDeviceZtService.selectBDeviceZtById(id));
//    }

//    /**
//     * 新增云组态
//     */
//    @Log(title = "云组态", businessType = BusinessType.INSERT)
//    @PostMapping
//    @SysInitData
//    @Transactional
//    public AjaxResult add(@RequestBody BDeviceZt bDeviceZt)
//    {
//        if(bDeviceZt.getIsMainPage()!=null&&bDeviceZt.getIsMainPage()==1&&Detect.notEmpty(bDeviceZt.getDeviceMac())){
//            String ztSql="update b_device_zt set is_main_page =0 where device_mac=?";
//            jdbcTemplate.update(ztSql,bDeviceZt.getDeviceMac());
//        }
//        BDeviceZtBind bDeviceZtBind=new BDeviceZtBind();
//        bDeviceZtBind.setDeviceMac(bDeviceZt.getDeviceMac());
//        bDeviceZtBind.setZtGuid(bDeviceZt.getGuid());
//        bDeviceZtBindService.insertBDeviceZtBind(bDeviceZtBind);
//        if(Detect.notEmpty(bDeviceZt.getPageSize())&&bDeviceZt.getPageSize().indexOf("x")>-1){
//            String[] pageSizes = bDeviceZt.getPageSize().split("x");
//            bDeviceZt.setDeviceZtData("{ \"name\": \"--\", \"layer\": { \"backColor\": \"\", \"backgroundImage\": \"\", \"widthHeightRatio\": \"\", \"width\": "+pageSizes[0]+", \"height\": "+pageSizes[1]+" }, \"components\": [] }");
//        }
//        return toAjax(bDeviceZtService.insertBDeviceZt(bDeviceZt));
//    }
//
//    /**
//     * 修改云组态
//     */
//    @Log(title = "云组态", businessType = BusinessType.UPDATE)
//    @PutMapping
//    @SysInitUpdateData
//    @Transactional
//    public AjaxResult edit(@RequestBody BDeviceZt bDeviceZt)
//    {
//        if(bDeviceZt.getIsMainPage()!=null&&bDeviceZt.getIsMainPage()==1&&Detect.notEmpty(bDeviceZt.getDeviceMac())){
//            String ztSql="update b_device_zt set is_main_page =0 where device_mac=? and guid!=?";
//            jdbcTemplate.update(ztSql,bDeviceZt.getDeviceMac(),bDeviceZt.getGuid());
//        }
//        return toAjax(bDeviceZtService.updateBDeviceZt(bDeviceZt));
//    }

    //    /**
//     * 删除云组态
//     */
//    @Log(title = "云组态", businessType = BusinessType.DELETE)
//    @DeleteMapping("/{ids}")
//    public AjaxResult remove(@PathVariable Long[] ids)
//    {
//        return toAjax(bDeviceZtService.deleteBDeviceZtByIds(ids));
//    }
    /*
     * 保存组态信息
     * */
//    @PostMapping(value = "saveZt")
//    @SysInitData
//    public AjaxResult saveZt(@RequestBody BDeviceZt bDeviceZt)
//    {
//        if(Detect.isEmpty(bDeviceZt.getGuid())||Detect.isEmpty(bDeviceZt.getDeviceMac())){
//            return AjaxResult.error("参数不符合规定");
//        }
//        BDeviceZt bDeviceZtQuery=new BDeviceZt();
//        bDeviceZtQuery.setGuid(bDeviceZt.getGuid());
//        bDeviceZtQuery.setDeviceMac(bDeviceZt.getDeviceMac());
//        List<BDeviceZt> bDeviceZts = bDeviceZtService.selectBDeviceZtList(bDeviceZtQuery);
//        if(bDeviceZts.size()>0){
//            BDeviceZt deviceZt = bDeviceZts.get(0);
//            deviceZt.setDeviceZtData(bDeviceZt.getDeviceZtData());
//            bDeviceZtService.updateBDeviceZt(deviceZt);
//        }else{
//            bDeviceZtService.insertBDeviceZt(bDeviceZt);
//            BDeviceZtBind bDeviceZtBind=new BDeviceZtBind();
//            bDeviceZtBind.setDeviceMac(bDeviceZt.getDeviceMac());
//            bDeviceZtBind.setZtGuid(bDeviceZt.getGuid());
//            bDeviceZtBindService.insertBDeviceZtBind(bDeviceZtBind);
//        }
//        return AjaxResult.success();
//    }
    /*
     * 复制组态信息
     * */
    @PostMapping(value = "/copyZtData")
    @SysInitData
    public AjaxResult copyZtData(@RequestBody BDeviceZt bDeviceZt) {
        BeanPropertyRowMapper<BDeviceZt> bDeviceDetailMapper = new BeanPropertyRowMapper<>(BDeviceZt.class);
        String sql = "select * from b_device_zt where id=?";
        bDeviceZt = jdbcTemplate.queryForObject(sql, bDeviceDetailMapper, bDeviceZt.getId());
        String ztData = bDeviceZt.getDeviceZtData();
        String guid = UUID.randomUUID().toString();
        bDeviceZt.setId(null);
        bDeviceZt.setGuid(guid);
        bDeviceZt.setPageName(bDeviceZt.getPageName() + "_副本");
        bDeviceZt.setDeviceZtData(ztData);
        bDeviceZt.setIsMainPage(0);
        bDeviceZt.setIsShare(0);
        bDeviceZt.setShareUrl("");
        bDeviceZtService.insertBDeviceZt(bDeviceZt);
        BDeviceZtBind bDeviceZtBind = new BDeviceZtBind();
        bDeviceZtBind.setDeviceMac(bDeviceZt.getDeviceMac());
        bDeviceZtBind.setZtGuid(guid);
        bDeviceZtBindService.insertBDeviceZtBind(bDeviceZtBind);
        return AjaxResult.success();
    }

    @Anonymous
    @PostMapping("/importZtJson")
    public AjaxResult importZtJson(@RequestBody MultipartFile file, String deviceImei, String guid) throws Exception {
        InputStream inputStream = file.getInputStream();
        if (file.isEmpty()) {
            return AjaxResult.error("无效的配置文件");
        }
        if (file.getOriginalFilename().indexOf("json") == -1) {
            return AjaxResult.error("无效的配置文件");
        }
        BDeviceZt bDeviceZt = new BDeviceZt();
        try {
            bDeviceZt = JSON.parseObject(inputStream, BDeviceZt.class);
        } catch (Exception e) {
            return AjaxResult.error("无效的配置文件");
        } finally {
            inputStream.close();
        }
        System.out.println("设备：" + deviceImei + "数据：" + bDeviceZt);
        BDeviceManager bDeviceManager = bDeviceManagerService.selectBDeviceManagerByImei(deviceImei);
        String ztData = bDeviceZt.getDeviceZtData();
        if (Detect.isEmpty(guid)) {
            guid = UUID.randomUUID().toString();
            bDeviceZt.setId(null);
            bDeviceZt.setGuid(guid);
            bDeviceZt.setPageName(bDeviceZt.getPageName());
            bDeviceZt.setDeviceZtData(ztData);
            bDeviceZt.setIsMainPage(0);
            bDeviceZt.setIsShare(0);
            bDeviceZt.setShareUrl("");
            bDeviceZt.setDeviceName(bDeviceManager.getDeviceName());
            bDeviceZt.setDeptIdStrs(bDeviceManager.getDeptIdStrs());
            bDeviceZt.setCreateBy(bDeviceManager.getCreateBy());
            bDeviceZt.setCreateTime(new Date());
            bDeviceZt.setUpdateBy(bDeviceManager.getUpdateBy());
            bDeviceZt.setUpdateTime(new Date());
            bDeviceZt.setDeviceMac(deviceImei);
            bDeviceZtService.insertBDeviceZt(bDeviceZt);
            BDeviceZtBind bDeviceZtBind = new BDeviceZtBind();
            bDeviceZtBind.setDeviceMac(deviceImei);
            bDeviceZtBind.setZtGuid(guid);
            bDeviceZtBindService.insertBDeviceZtBind(bDeviceZtBind);
        } else {
            BDeviceZt bDeviceZtQuery = new BDeviceZt();
            bDeviceZtQuery.setGuid(guid);
            List<BDeviceZt> bDeviceZts = bDeviceZtService.selectBDeviceZtList(bDeviceZtQuery);
            if (bDeviceZts.size() > 0) {
                bDeviceZtQuery = bDeviceZts.get(0);
            }
            bDeviceZtQuery.setDeviceZtData(ztData);
            bDeviceZtService.updateBDeviceZt(bDeviceZtQuery);
        }
        return AjaxResult.success("导入成功");
    }

    /*验证分享密码*/
    @PostMapping("/confirmPass")
    public AjaxResult importZtJson(@RequestBody BDeviceZt bDeviceZt) throws Exception {
        if (Detect.isEmpty(bDeviceZt.getGuid()) || Detect.isEmpty(bDeviceZt.getDeviceMac()) || Detect.isEmpty(bDeviceZt.getSharePass())) {
            return AjaxResult.success(false);
        }
        BDeviceZt bDeviceZtQuery = new BDeviceZt();
        bDeviceZtQuery.setDeviceMac(bDeviceZt.getDeviceMac());
        bDeviceZtQuery.setGuid(bDeviceZt.getGuid());
        List<BDeviceZt> bDeviceZtList = bDeviceZtService.selectBDeviceZtList(bDeviceZtQuery);
        if (bDeviceZtList.size() > 0) {
            if (Detect.notEmpty(bDeviceZtList.get(0).getSharePass()) && bDeviceZtList
                    .get(0)
                    .getSharePass()
                    .equals(bDeviceZt.getSharePass())) {
                return AjaxResult.success(true);
            } else {
                return AjaxResult.success(false);
            }
        } else {
            return AjaxResult.success(false);
        }
    }

    /**
     * 授权设备
     */
    @PostMapping(value = "/empowerDevice")
    public AjaxResult empowerDevice(@RequestBody BDeviceEmpower bDeviceEmpower) {
        BDeviceZt bDeviceZt = bDeviceZtService.selectBDeviceZtById(Convert.toLong(bDeviceEmpower.getDeviceId()));
        SysUser sysUser = new SysUser();
        sysUser.setDeptId(Convert.toLong(bDeviceEmpower.getDeptId()));
        sysUser.setStatus("0");
        List<SysUser> sysUsers = userService.selectUserList(sysUser);
        if (bDeviceEmpower.getEmpowerType().equals("设备授权")) {
            if (bDeviceZt.getDeptIdStrs().indexOf(bDeviceEmpower.getDeptId()) == -1) {
                bDeviceZt.setDeptIdStrs(bDeviceZt.getDeptIdStrs() + bDeviceEmpower.getDeptId() + ",");
                if (sysUsers.size() > 0) {
                    bDeviceZt.setCreateBy(sysUsers.get(0).getUserName());
                }
                bDeviceZtService.updateBDeviceZt(bDeviceZt);
            }
        } else {
            bDeviceZt.setDeptIdStrs(bDeviceZt.getDeptIdStrs().replace(bDeviceEmpower.getDeptId() + ",", ""));
            bDeviceZtService.updateBDeviceZt(bDeviceZt);
        }
        return AjaxResult.success();
    }

    /*
     * 保存组态缩略图
     * */
    @PostMapping(value = "saveZtImage")
    public AjaxResult saveZtImage(@RequestBody BDeviceZt bDeviceZt) {
        if (Detect.isEmpty(bDeviceZt.getGuid())) {
            return AjaxResult.error("参数不符合规定");
        }
        MultipartFile image = ImageUtils.base64ToMultipartFile(bDeviceZt.getBase64());
        String imageUrl = "";
        try {
            imageUrl = FileUploadUtils.upload(RuoYiConfig.getAvatarPath(), image);
        } catch (Exception e) {
            return AjaxResult.error(500, "上传组件异常，" + e);
        }
        BDeviceZt bDeviceZtQuery = new BDeviceZt();
        bDeviceZtQuery.setGuid(bDeviceZt.getGuid());
        List<BDeviceZt> bDeviceZts = bDeviceZtService.selectBDeviceZtList(bDeviceZtQuery);
        if (bDeviceZts.size() > 0) {
            BDeviceZt deviceZt = bDeviceZts.get(0);
            if (Detect.notEmpty(deviceZt.getPageImage())) {
                String newUrl = deviceZt.getPageImage().replace("/profile", "").replace("/avatar", "");
                File fileQuery = new File(RuoYiConfig.getAvatarPath() + newUrl);
                if (fileQuery.exists()) {
                    System.out.println("删除之前的图片资源");
                    fileQuery.delete();
                }
            }
            deviceZt.setPageImage(imageUrl);
            bDeviceZtService.updateBDeviceZt(deviceZt);
        }
        return AjaxResult.success();
    }

    /*打包部署*/
    @PostMapping("/downloadZtZip")
    public AjaxResult download(@RequestBody BDeviceZt bDeviceZt) {
        String downloadUrl = bDeviceZtService.download(bDeviceZt);
        return AjaxResult.success(downloadUrl);
    }
}
